<?php
/**
 * File: User.php
 * User: Mr.Yang
 * Date: 2025/3/25 0025
 * Time: 8:53
 * Note:
 */

namespace app\admin\model;


use think\Model;

class User extends Model
{
    protected $autoWriteTimestamp = "datetime";
    protected $dateFormat = 'Y-m-d H:i:s';

    protected $createTime = "date_entered";
    protected $updateTime = "update_entered";

    public static function init()
    {
        self::event('before_delete', function ($query){
            $uid = $query->id;

        });

        self::event('before_insert', function ($query){
            $salt = createNonceStr(6);
            $query->salt = $salt;
            $paysalt = createNonceStr(6);
            $query->paysalt = $paysalt;
            $query->password = createPassword($query->password, $salt);
            $query->payword = createPassword($query->payword, $paysalt);
            return true;
        });
    }

    /**
     * @param int $offset
     * @param int $limit
     * @param array $where
     * @return array
     */
    public function getList($offset = 0, $limit=10, $where = [])
    {
        return $this->where($where)->hidden(['password', 'salt', 'payword', 'paysalt'])->limit($offset, $limit)->order('id', 'desc')->select()->toArray();
    }

    /**
     * @param array $where
     * @return $this
     */
    public function getListCount($where = [])
    {
        return $this->where($where)->count();
    }

    /**
     * @param $id
     * @return array
     */
    public function getOneById($id)
    {
        return $this->where("id", $id)->findOrEmpty()->toArray();
    }

    /**
     * Note: 获取启用的用户
     * User: Mr.Yang
     * @param $where
     * @return array
     */
    public function getOneByWhere($where)
    {
        return $this->whereOr($where)->where("status", "=", 1)->findOrEmpty()->toArray();
    }

    /**
     * @param $data
     * @return bool
     */
    public function add($data)
    {
        return $this->save($data);
    }

    /**
     * @param $id
     * @param $data
     * @return bool
     */
    public function edit($id, $data)
    {
        return $this->save($data, [['id', '=', $id]]);
    }

    /**
     *
     * @param $id
     * @return bool
     * @throws \Exception
     */
    public function del($id)
    {
        return self::get($id)->delete();
    }

    public function getAll()
    {
        return $this->selectOrFail();
    }
}